import math
import re
import time
import requests
from datetime import datetime
from lxml import etree


def find_latest_date_in_range(date_list, start_date, end_date):
    print(f"时间范围:{start_date}-{end_date}")
    # 将字符串日期转换为datetime对象
    date_objects = [datetime.strptime(date_str, '%Y-%m-%d') for date_str in date_list]
    start_obj = datetime.strptime(start_date, '%Y-%m-%d')
    end_obj = datetime.strptime(end_date, '%Y-%m-%d')

    # 筛选时间范围内的日期
    filtered_dates = [date for date in date_objects if start_obj <= date <= end_obj]
    # 如果有符合条件的日期，返回所有符合条件的日期（格式化为字符串）
    if filtered_dates:
        return [date.strftime('%Y-%m-%d') for date in filtered_dates]
    else:
        print(f"{start_date} 00:00:00-{end_date} 00:00:00无随访记录")
        return None

def manzufeidownload1(id_person,ehrid, headers_8,DOMAIN,start_limit_time,end_limit_time, suifangleixing):


    url_1 = f"{DOMAIN}/phis/app/svc/flw/copd"

    data = {
        'search_EQ_ehrId': f'{ehrid}',
        '_dch': f"{time.time()}".replace(".", "")[:13],
    }

    response_9 = requests.post(url_1, data=data, headers=headers_8)
    all_sf_info = []
    li_jibing = response_9.json()
    if li_jibing == []:
        return "没有慢阻肺随访按钮"
    for date in li_jibing:
        # 将包含时间的日期字符串转换为仅日期部分
        date_created = date["dateCreated"]
        if ' ' in date_created:
            # 如果包含时间部分，只取日期部分
            formatted_date = date_created.split()[0]
            all_sf_info.append(formatted_date)
        else:
            all_sf_info.append(date_created)
    target_date_list = find_latest_date_in_range(all_sf_info, start_limit_time, end_limit_time)
    if target_date_list==None:
        return []
    #
    all_infomation = []
    list_riqibianshi = []

    try:
        for target_date in target_date_list:
            if target_date:
                for info in response_9.json():
                    # 限制条件，获取指定日期数据
                    if info["dateCreated"] == target_date+" 00:00:00":
                        manzubing_data = {
                            "随访类型":suifangleixing["随访类型"],
                            '身份证号': "'"+str(id_person),
                            '随访日期': None,
                            '用药情况': None,
                            '药物变更': None,
                            '药物变更时间': None,
                            '药物变更原因': None,
                            '药物变更原因其他': None,
                            '症状': None,
                            '症状其他': None,
                            '合并症': None,
                            '合并症其他': None,
                            '呼吸疾病用药不良反应': None,
                            '呼吸疾病用药不良反应其他': None,
                            'mMRC问卷': None,
                            '随访机构': None,
                            '随访人': None,
                            '随访方式': None,
                            '姓名': None,
                            '性别': None,
                            '出生日期': None,
                            '所属人群': None,
                            '服药依从性': None,
                            '下次随访日期': None,
                            '此次随访分类': None,
                            '身高': None,
                            '体重': None,
                            '体质指数': None,
                            '心率': None,
                            '口唇紫绀': None,
                            '外周水肿': None,
                            'SpO2': None,
                            '其它体征': None,
                            '因急性加重住院': None,
                            '吸烟状态': None,
                            '日吸烟量': None,
                            '低强度运动': None,
                            '中强度运动': None,
                            '高强度运动': None,
                            '流感疫苗': None,
                            '流感疫苗接种时间': None,
                            '肺炎球菌疫苗': None,
                            '肺炎球菌疫苗接种时间': None,
                            'FEV1': None,
                            'FVC': None,
                            'FEV1/FVC': None,
                            'FEV1占预计值百分比': None,
                            'CAT问卷总分': None,
                            'CAT问卷': None,
                            '家庭氧疗': None,
                            '家庭氧疗每日时间': None,
                            '家庭氧疗氧流量': None,
                            '家庭氧疗副作用': None,
                            '家庭氧疗副作用描述': None,
                            '无创呼吸机使用': None,
                            '无创呼吸机使用每日时间': None,
                            '无创呼吸机使用氧流量': None,
                            '无创呼吸机使用副作用': None,
                            '无创呼吸机使用副作用描述': None,
                            '是否转诊': None,
                            '转诊原因': None,
                            '机构及科别': None
                        }

                        # 日期的id
                        data_id = info.get("id")
                        print(f"日期id:{data_id}")
                        if data_id in list_riqibianshi:
                            continue
                        list_riqibianshi.append(data_id)

                        manzubing_data["随访日期"] = info.get("dateCreated")
                        print("随访日期:", info.get("dateCreated"))


                        # 用药情况
                        yongyaoqingkuang_id = info.get("flwId")

                        yongya_url = f"{DOMAIN}/phis/app/svc/flw/copd/med"
                        data_yongyao = {
                            "flwId": yongyaoqingkuang_id,
                            "source": 1,
                            "_dch": f"{time.time()}".replace(".", "")[:13],
                        }
                        response_yaopinbao = requests.post(yongya_url, data=data_yongyao, headers=headers_8).json()["content"]

                        yongyao_list = []
                        for yaopin_li in response_yaopinbao:
                            yongyao_dict = {}
                            yongyao_dict["用药名称"] = yaopin_li["medName"]
                            yongyao_dict["药品类型"] = yaopin_li["medType"]
                            yongyao_dict["用法"] = yaopin_li["methodVolume"]
                            yongyao_dict["用量"] = yaopin_li["useLevel"]
                            try:
                                yongyao_dict["备注"] = yaopin_li["remark"]
                            except:
                                yongyao_dict["备注"] = ""
                            yongyao_list.append(yongyao_dict)
                        manzubing_data["用药情况"] = yongyao_list
                        print("用药情况:", yongyao_list)


                        # 获取txt包能抓到的内容
                        txt_url = f"{DOMAIN}/phis/app/svc/flw/copd/update/{data_id}"
                        response_txt = requests.get(txt_url, headers=headers_8).text
                        tree = etree.HTML(response_txt)
                        # 比较难抓的内容
                        # 药物变更
                        yaowubiangeng = r"var\s+medChange\s*=\s*'(\d+)';"
                        ywbg = re.search(yaowubiangeng, response_txt)
                        if ywbg.group(1)=="0":
                            manzubing_data["药物变更"] = "无"
                        elif ywbg.group(1)=="1":
                            manzubing_data["药物变更"] = "有"
                        print("药物变更:", manzubing_data["药物变更"])

                        # 药物变更时间
                        try:
                            med_change_time = tree.xpath('//input[@id="medChangeTime"]/@value')[0]
                            manzubing_data["药物变更时间"] = med_change_time
                            if manzubing_data["药物变更时间"] == "":
                                manzubing_data["药物变更时间"] = None
                        except IndexError:
                            manzubing_data["药物变更时间"] = "未获取到"
                            print("未找到药物变更时间")
                        except Exception as e:
                            manzubing_data["药物变更时间"] = "获取出错"
                            print(f"获取药物变更时间出错: {e}")
                        print("药物变更时间:", manzubing_data["药物变更时间"])

                        # 药物变更原因
                        try:
                            # 查找被选中的药物变更原因单选按钮
                            selected_reason = tree.xpath('//input[@name="medChangeReason" and @checked="checked"]')

                            if selected_reason:
                                # 获取选中项的value值
                                reason_value = selected_reason[0].get('value')

                                # 根据value值确定对应的文本
                                reason_mapping = {
                                    '1': '症状控制不满意',
                                    '2': '药物不良反应',
                                    '3': '缺乏药物',
                                    '4': '自行停药',
                                    '5': '其他'
                                }

                                manzubing_data["药物变更原因"] = reason_mapping.get(reason_value, "未知原因")

                                # 如果是"其他"选项，还需要获取textarea中的内容
                                if reason_value == '5':
                                    try:
                                        other_reason = tree.xpath('//textarea[@id="medChangeReasonOther"]/text()')
                                        if other_reason:
                                            other_text = other_reason[0].strip()
                                            if other_text:
                                                manzubing_data["药物变更原因其他"] = other_text
                                                manzubing_data["药物变更原因"] = f"其他"
                                            else:
                                                manzubing_data["药物变更原因其他"] = None
                                        else:
                                            manzubing_data["药物变更原因其他"] = None
                                    except Exception as e:
                                        manzubing_data["药物变更原因其他"] = "获取出错"
                                        print(f"获取其他原因内容出错: {e}")
                                else:
                                    # 如果不是"其他"选项，确保"药物变更原因其他"字段为None
                                    manzubing_data["药物变更原因其他"] = None
                            else:
                                manzubing_data["药物变更原因"] = None
                                manzubing_data["药物变更原因其他"] = None

                        except Exception as e:
                            manzubing_data["药物变更原因"] = "获取出错"
                            manzubing_data["药物变更原因其他"] = "获取出错"
                            print(f"获取药物变更原因出错: {e}")

                        print("药物变更原因:", manzubing_data["药物变更原因"])
                        print("药物变更原因其他:", manzubing_data["药物变更原因其他"])


                        # 症状提取
                        try:
                            # 从JavaScript中提取sympt变量
                            symptom_pattern = r"var\s+sympt\s*=\s*\"([^\"]*)\";"
                            symptom_match = re.search(symptom_pattern, response_txt)

                            if symptom_match:
                                symptom_ids = symptom_match.group(1)  # 获取到 "2,3,4,17"

                                # 症状映射表
                                symptom_mapping = {
                                    '1': '无症状',
                                    '2': '咳嗽',
                                    '3': '咳痰',
                                    '4': '气短',
                                    '5': '喘息',
                                    '6': '呼吸困难',
                                    '7': '咯血',
                                    '8': '乏力',
                                    '9': '胸闷',
                                    '10': '发热',
                                    '11': '打喷嚏、流涕',
                                    '17': '其他'
                                }

                                # 解析症状ID并转换为症状名称
                                symptom_id_list = symptom_ids.split(',') if symptom_ids else []
                                symptom_names = [symptom_mapping.get(sid, '') for sid in symptom_id_list if
                                                 sid in symptom_mapping]

                                # 保存症状
                                manzubing_data["症状"] = ', '.join(symptom_names) if symptom_names else None

                                # 如果包含"其他"，还需要获取其他症状的具体描述
                                if '17' in symptom_id_list:
                                    try:
                                        other_symptom = tree.xpath('//textarea[@id="otherSymptom_text"]/text()')
                                        if other_symptom:
                                            other_text = other_symptom[0].strip()
                                            if other_text:
                                                manzubing_data["症状其他"] = other_text
                                            else:
                                                manzubing_data["症状其他"] = None
                                        else:
                                            manzubing_data["症状其他"] = None
                                    except Exception as e:
                                        manzubing_data["症状其他"] = "获取出错"
                                        print(f"获取其他症状内容出错: {e}")
                                else:
                                    manzubing_data["症状其他"] = None
                            else:
                                manzubing_data["症状"] = None
                                manzubing_data["症状其他"] = None

                        except Exception as e:
                            manzubing_data["症状"] = "获取出错"
                            manzubing_data["症状其他"] = "获取出错"
                            print(f"获取症状出错: {e}")

                        print("症状:", manzubing_data["症状"])
                        print("症状其他:", manzubing_data["症状其他"])

                        # 合并症
                        # 合并症提取
                        try:
                            # 从JavaScript中提取me变量
                            complication_pattern = r"var\s+c\s*=\s*\"([^\"]*)\";"
                            complication_match = re.search(complication_pattern, response_txt)

                            if complication_match:
                                complication_ids = complication_match.group(1)  # 获取到 "3,4,17"

                                # 合并症映射表
                                complication_mapping = {
                                    '1': '无',
                                    '2': '冠心病',
                                    '3': '高血压',
                                    '4': '心律失常',
                                    '5': '骨质疏松',
                                    '6': '焦虑抑郁',
                                    '7': '肺癌',
                                    '8': '感染',
                                    '9': '糖尿病',
                                    '10': '过敏性鼻炎',
                                    '17': '其他'
                                }

                                # 解析合并症ID并转换为合并症名称
                                complication_id_list = complication_ids.split(',') if complication_ids else []
                                complication_names = [complication_mapping.get(cid, '') for cid in complication_id_list if
                                                      cid in complication_mapping]

                                # 保存合并症
                                manzubing_data["合并症"] = ', '.join(complication_names) if complication_names else None

                                # 如果包含"其他"，还需要获取其他合并症的具体描述
                                if '17' in complication_id_list:
                                    try:
                                        other_complication = tree.xpath('//textarea[@id="otherComplication_text"]/text()')
                                        if other_complication:
                                            other_text = other_complication[0].strip()
                                            if other_text:
                                                manzubing_data["合并症其他"] = other_text
                                            else:
                                                manzubing_data["合并症其他"] = None
                                        else:
                                            manzubing_data["合并症其他"] = None
                                    except Exception as e:
                                        manzubing_data["合并症其他"] = "获取出错"
                                        print(f"获取其他合并症内容出错: {e}")
                                else:
                                    manzubing_data["合并症其他"] = None
                            else:
                                manzubing_data["合并症"] = None
                                manzubing_data["合并症其他"] = None

                        except Exception as e:
                            manzubing_data["合并症"] = "获取出错"
                            manzubing_data["合并症其他"] = "获取出错"
                            print(f"获取合并症出错: {e}")

                        print("合并症:", manzubing_data["合并症"])
                        print("合并症其他:", manzubing_data["合并症其他"])



                        # 呼吸疾病用药不良反应
                        # 呼吸疾病用药不良反应提取
                        try:
                            # 从JavaScript中提取me变量
                            medication_effect_pattern = r"var\s+me\s*=\s*\"([^\"]*)\";"
                            medication_effect_match = re.search(medication_effect_pattern, response_txt)

                            if medication_effect_match:
                                medication_effect_ids = medication_effect_match.group(1)  # 获取到 "3,4,17"

                                # 呼吸疾病用药不良反应映射表
                                medication_effect_mapping = {
                                    '1': '无',
                                    '2': '心悸、心慌',
                                    '3': '头晕、头痛',
                                    '4': '口干',
                                    '5': '便秘',
                                    '6': '口腔黏膜白斑',
                                    '7': '声音嘶哑',
                                    '8': '尿潴留',
                                    '17': '其他'
                                }

                                # 解析呼吸疾病用药不良反应ID并转换为呼吸疾病用药不良反应名称
                                medication_effect_id_list = medication_effect_ids.split(
                                    ',') if medication_effect_ids else []
                                medication_effect_names = [medication_effect_mapping.get(meid, '') for meid in
                                                           medication_effect_id_list if meid in medication_effect_mapping]

                                # 保存呼吸疾病用药呼吸疾病用药不良反应
                                manzubing_data["呼吸疾病用药不良反应"] = ', '.join(
                                    medication_effect_names) if medication_effect_names else None

                                # 如果包含"其他"，还需要获取其他呼吸疾病用药不良反应的具体描述
                                if '17' in medication_effect_id_list:
                                    try:
                                        other_medication_effect = tree.xpath(
                                            '//textarea[@id="otherMedicationEffect_text"]/text()')
                                        if other_medication_effect:
                                            other_text = other_medication_effect[0].strip()
                                            if other_text:
                                                manzubing_data["呼吸疾病用药不良反应其他"] = other_text
                                            else:
                                                manzubing_data["呼吸疾病用药不良反应其他"] = None
                                        else:
                                            manzubing_data["呼吸疾病用药不良反应其他"] = None
                                    except Exception as e:
                                        manzubing_data["呼吸疾病用药不良反应其他"] = "获取出错"
                                        print(f"获取其他呼吸疾病用药不良反应内容出错: {e}")
                                else:
                                    manzubing_data["呼吸疾病用药不良反应其他"] = None
                            else:
                                manzubing_data["呼吸疾病用药不良反应"] = None
                                manzubing_data["呼吸疾病用药不良反应其他"] = None

                        except Exception as e:
                            manzubing_data["呼吸疾病用药不良反应"] = "获取出错"
                            manzubing_data["呼吸疾病用药不良反应其他"] = "获取出错"
                            print(f"获取呼吸疾病用药不良反应出错: {e}")

                        print("呼吸疾病用药不良反应:", manzubing_data["呼吸疾病用药不良反应"])
                        print("呼吸疾病用药不良反应其他:", manzubing_data["呼吸疾病用药不良反应其他"])


                        # mMRC问卷
                        # mMRC问卷处理
                        try:
                            # 从JavaScript变量中提取mmrc值
                            mmrc_pattern = r"var\s+mmrc\s*=\s*\"(\d+)\";"
                            mmrc_match = re.search(mmrc_pattern, response_txt)

                            if mmrc_match:
                                mmrc_value = mmrc_match.group(1)  # 获取到 "2"

                                # mMRC问卷选项内容映射表
                                mmrc_mapping = {
                                    '0': '0级；只有在剧烈活动时才感到呼吸困难；',
                                    '1': '1级；在平地快步行走或步行爬小坡时感到气短；',
                                    '2': '2级；由于气短，平地行走时比同龄人慢，或者需要停下来休息；',
                                    '3': '3级；在平地行走100米左右或数分钟后需要停下来喘气；',
                                    '4': '4级；因严重呼吸困难以至于不能离开家，或在穿衣服、脱衣服时出现呼吸困难；'
                                }

                                # 保存mMRC问卷结果
                                manzubing_data["mMRC问卷"] = mmrc_mapping.get(mmrc_value, "未知等级")

                                print("mMRC问卷:", manzubing_data["mMRC问卷"])
                            else:
                                manzubing_data["mMRC问卷"] = None
                                print("未找到mMRC问卷信息")

                        except Exception as e:
                            manzubing_data["mMRC问卷"] = "获取出错"
                            print(f"获取mMRC问卷出错: {e}")

                        # P0
                        # 获取随访相关信息
                        try:
                            # 随访机构
                            flw_org_name = tree.xpath('//input[@name="flwOrgName"]/@value')
                            manzubing_data["随访机构"] = flw_org_name[0] if flw_org_name else None
                            print("随访机构:", manzubing_data["随访机构"])
                        except Exception as e:
                            manzubing_data["随访机构"] = "获取出错"
                            print(f"获取随访机构出错: {e}")

                        try:
                            # 随访人
                            flw_doctor_name = tree.xpath('//input[@id="followPerson"]/@value')
                            manzubing_data["随访人"] = flw_doctor_name[0] if flw_doctor_name else None
                            print("随访人:", manzubing_data["随访人"])
                        except Exception as e:
                            manzubing_data["随访人"] = "获取出错"
                            print(f"获取随访人出错: {e}")

                        try:
                            # 随访方式
                            follow_way_mapping = {
                                '1': '门诊',
                                '2': '家庭',
                                '3': '电话',
                                '4': '视频'
                            }

                            # 获取选中的随访方式option
                            selected_follow_way = tree.xpath(
                                '//select[@id="followWay"]/option[@selected="selected"]/@value')
                            if selected_follow_way:
                                manzubing_data["随访方式"] = follow_way_mapping.get(selected_follow_way[0], "未知")
                            else:
                                # 如果没有selected属性，尝试获取第一个option的值
                                first_option = tree.xpath('//select[@id="followWay"]/option[1]/@value')
                                manzubing_data["随访方式"] = follow_way_mapping.get(first_option[0],
                                                                                    "未知") if first_option else None

                            print("随访方式:", manzubing_data["随访方式"])
                        except Exception as e:
                            manzubing_data["随访方式"] = "获取出错"
                            print(f"获取随访方式出错: {e}")



                        # P1
                        # 获取基本信息
                        try:
                            # 姓名
                            name = tree.xpath('//span[contains(text(),"姓名：")]/following-sibling::input[1]/@value')
                            manzubing_data["姓名"] = name[0] if name else None
                            print("姓名:", manzubing_data["姓名"])
                        except Exception as e:
                            manzubing_data["姓名"] = "获取出错"
                            print(f"获取姓名出错: {e}")

                        try:
                            # 性别
                            gender = tree.xpath('//span[contains(text(),"性别：")]/following-sibling::input[1]/@value')
                            manzubing_data["性别"] = gender[0] if gender else None
                            print("性别:", manzubing_data["性别"])
                        except Exception as e:
                            manzubing_data["性别"] = "获取出错"
                            print(f"获取性别出错: {e}")

                        try:
                            # 出生日期
                            birth_date = tree.xpath(
                                '//span[contains(text(),"出生日期：")]/following-sibling::input[1]/@value')
                            manzubing_data["出生日期"] = birth_date[0].strip() if birth_date else None
                            print("出生日期:", manzubing_data["出生日期"])
                        except Exception as e:
                            manzubing_data["出生日期"] = "获取出错"
                            print(f"获取出生日期出错: {e}")

                        try:
                            # 所属人群
                            population = tree.xpath(
                                '//span[contains(text(),"所属人群：")]/following-sibling::input[1]/@value')
                            manzubing_data["所属人群"] = population[0] if population else None
                            print("所属人群:", manzubing_data["所属人群"])
                        except Exception as e:
                            manzubing_data["所属人群"] = "获取出错"
                            print(f"获取所属人群出错: {e}")

                        try:
                            # 服药依从性
                            compliance_mapping = {
                                '1': '规律',
                                '2': '间断',
                                '3': '不服药'
                            }

                            # 查找被选中的服药依从性单选按钮
                            selected_compliance = tree.xpath('//input[@name="compliance" and @checked="checked"]/@value')
                            if selected_compliance:
                                manzubing_data["服药依从性"] = compliance_mapping.get(selected_compliance[0], "未知")
                            else:
                                manzubing_data["服药依从性"] = None

                            print("服药依从性:", manzubing_data["服药依从性"])
                        except Exception as e:
                            manzubing_data["服药依从性"] = "获取出错"
                            print(f"获取服药依从性出错: {e}")

                        try:
                            # 下次随访日期
                            next_flw_date = tree.xpath('//input[@id="nextFlwDate"]/@value')
                            manzubing_data["下次随访日期"] = next_flw_date[0] if next_flw_date else None
                            print("下次随访日期:", manzubing_data["下次随访日期"])
                        except Exception as e:
                            manzubing_data["下次随访日期"] = "获取出错"
                            print(f"获取下次随访日期出错: {e}")

                        try:
                            # 此次随访分类
                            flw_sort_mapping = {
                                '1': '控制满意',
                                '2': '控制不满意',
                                '3': '呼吸疾病用药不良反应',
                                '4': '并发症'
                            }

                            # 查找被选中的此次随访分类单选按钮
                            selected_flw_sort = tree.xpath('//input[@name="flwSortBp" and @checked="checked"]/@value')
                            if selected_flw_sort:
                                manzubing_data["此次随访分类"] = flw_sort_mapping.get(selected_flw_sort[0], "未知")
                            else:
                                manzubing_data["此次随访分类"] = None

                            print("此次随访分类:", manzubing_data["此次随访分类"])
                        except Exception as e:
                            manzubing_data["此次随访分类"] = "获取出错"
                            print(f"获取此次随访分类出错: {e}")


                        # P2
                        # 症状上面已经拿到了

                        # P3
                        # 获取体征信息
                        try:
                            # 身高
                            height = tree.xpath('//input[@id="height"]/@value')
                            if height:
                                height_value = height[0].strip()
                                if height_value == "-1.0":
                                    manzubing_data["身高"] = "未查"
                                else:
                                    manzubing_data["身高"] = float(height_value)
                            else:
                                manzubing_data["身高"] = None
                            print("身高:", manzubing_data["身高"])
                        except Exception as e:
                            manzubing_data["身高"] = "获取出错"
                            print(f"获取身高出错: {e}")

                        try:
                            # 体重
                            weight = tree.xpath('//input[@id="weightCur"]/@value')
                            if weight:
                                weight_value = weight[0].strip()
                                if weight_value == "-1.0":
                                    manzubing_data["体重"] = "未查"
                                else:
                                    manzubing_data["体重"] = float(weight_value)
                            else:
                                manzubing_data["体重"] = None
                            print("体重:", manzubing_data["体重"])
                        except Exception as e:
                            manzubing_data["体重"] = "获取出错"
                            print(f"获取体重出错: {e}")

                        # 体质指数(BMI)处理
                        try:
                            # 方法1: 直接从页面获取
                            bmi = tree.xpath('//input[@id="bmiTar"]/@value')
                            if bmi and bmi[0].strip():
                                bmi_value = bmi[0].strip()
                                # 向下取后两位小数
                                bmi_float = float(bmi_value)
                                manzubing_data["体质指数"] = math.floor(bmi_float * 100) / 100
                            else:
                                # 方法2: 通过身高和体重计算
                                height_val = manzubing_data.get("身高")
                                weight_val = manzubing_data.get("体重")

                                # 检查身高和体重是否都有效（都不是"未查"且都存在）
                                if (height_val is not None and height_val != "未查" and height_val > 0 and
                                        weight_val is not None and weight_val != "未查" and weight_val > 0):
                                    # BMI = 体重(kg) / (身高(m) * 身高(m))
                                    bmi_calculated = weight_val / ((height_val / 100) ** 2)
                                    # 向下取后两位小数
                                    manzubing_data["体质指数"] = math.floor(bmi_calculated * 100) / 100
                                elif (height_val == "未查" or weight_val == "未查"):
                                    manzubing_data["体质指数"] = None
                                else:
                                    manzubing_data["体质指数"] = None
                            print("体质指数:", manzubing_data["体质指数"])
                        except Exception as e:
                            manzubing_data["体质指数"] = "获取出错"
                            print(f"获取体质指数出错: {e}")

                        try:
                            # 心率
                            heartrate = tree.xpath('//input[@id="heartrate"]/@value')
                            if heartrate:
                                heartrate_value = heartrate[0].strip()
                                # 检查是否被标记为"不适用"
                                not_apply_checked = tree.xpath('//input[@id="heartrateNotApply" and @checked="checked"]')
                                if not_apply_checked:
                                    manzubing_data["心率"] = "不适用"
                                elif heartrate_value == "-1.0":
                                    manzubing_data["心率"] = "未查"
                                else:
                                    manzubing_data["心率"] = float(heartrate_value)
                            else:
                                manzubing_data["心率"] = None
                            print("心率:", manzubing_data["心率"])
                        except Exception as e:
                            manzubing_data["心率"] = "获取出错"
                            print(f"获取心率出错: {e}")

                        # P4
                        # 获取其他体征信息
                        try:
                            # 口唇紫绀
                            cyanosis_lips_mapping = {
                                '1': '有',
                                '0': '无',
                                '2': '不适用'
                            }

                            # 查找被选中的口唇紫绀单选按钮
                            selected_cyanosis = tree.xpath(
                                '//input[@name="cyanosisLipsSign" and @checked="checked"]/@value')
                            if selected_cyanosis:
                                manzubing_data["口唇紫绀"] = cyanosis_lips_mapping.get(selected_cyanosis[0], "未知")
                            else:
                                manzubing_data["口唇紫绀"] = None
                            print("口唇紫绀:", manzubing_data["口唇紫绀"])
                        except Exception as e:
                            manzubing_data["口唇紫绀"] = "获取出错"
                            print(f"获取口唇紫绀出错: {e}")

                        try:
                            # 外周水肿
                            peripheral_edema_mapping = {
                                '1': '有',
                                '0': '无',
                                '2': '不适用'
                            }

                            # 查找被选中的外周水肿单选按钮
                            selected_edema = tree.xpath(
                                '//input[@name="peripheralEdemaSign" and @checked="checked"]/@value')
                            if selected_edema:
                                manzubing_data["外周水肿"] = peripheral_edema_mapping.get(selected_edema[0], "未知")
                            else:
                                manzubing_data["外周水肿"] = None
                            print("外周水肿:", manzubing_data["外周水肿"])
                        except Exception as e:
                            manzubing_data["外周水肿"] = "获取出错"
                            print(f"获取外周水肿出错: {e}")

                        try:
                            # SpO2
                            spo2 = tree.xpath('//input[@id="spo2Before"]/@value')
                            if spo2 and spo2[0].strip():  # 检查是否有值且不为空
                                spo2_value = spo2[0].strip()
                                # 检查是否被标记为"不适用"
                                not_apply_checked = tree.xpath('//input[@id="spo2NotApply" and @checked="checked"]')
                                if not_apply_checked:
                                    manzubing_data["SpO2"] = "不适用"
                                elif spo2_value == "-1.0":
                                    manzubing_data["SpO2"] = "未查"
                                else:
                                    try:
                                        manzubing_data["SpO2"] = float(spo2_value)
                                    except ValueError:
                                        manzubing_data["SpO2"] = "数据无效"
                            else:
                                manzubing_data["SpO2"] = None
                            print("SpO2:", manzubing_data["SpO2"])
                        except Exception as e:
                            manzubing_data["SpO2"] = "获取出错"
                            print(f"获取SpO2出错: {e}")

                        try:
                            # 其它体征
                            sign_other = tree.xpath('//input[@id="signOther"]/@value')
                            if sign_other:
                                sign_other_value = sign_other[0].strip()
                                manzubing_data["其它体征"] = sign_other_value if sign_other_value else None
                            else:
                                manzubing_data["其它体征"] = None
                            print("其它体征:", manzubing_data["其它体征"])
                        except Exception as e:
                            manzubing_data["其它体征"] = "获取出错"
                            print(f"获取其它体征出错: {e}")


                        # P5
                        # 获取因急性加重住院信息
                        try:
                            # 急性加重住院映射表
                            acute_hosp_mapping = {
                                '0': '未住院',
                                '1': '住院'
                            }

                            # 查找被选中的急性加重住院单选按钮
                            selected_acute_hosp = tree.xpath('//input[@name="acuteHosp" and @checked="checked"]/@value')
                            if selected_acute_hosp:
                                manzubing_data["因急性加重住院"] = acute_hosp_mapping.get(selected_acute_hosp[0], "未知")
                            else:
                                manzubing_data["因急性加重住院"] = None
                            print("因急性加重住院:", manzubing_data["因急性加重住院"])
                        except Exception as e:
                            manzubing_data["因急性加重住院"] = "获取出错"
                            print(f"获取因急性加重住院出错: {e}")

                        # P6
                        # P6
                        # 获取生活方式信息
                        try:
                            # 日吸烟量相关信息
                            try:
                                # 吸烟状态
                                smoking_mapping = {
                                    '1': '吸烟',
                                    '2': '不吸烟',
                                    '3': '已戒烟'
                                }

                                # 查找被选中的吸烟状态单选按钮
                                selected_smoking = tree.xpath('//input[@name="smSmoking" and @checked="checked"]/@value')
                                if selected_smoking:
                                    manzubing_data["吸烟状态"] = smoking_mapping.get(selected_smoking[0], "未知")
                                else:
                                    manzubing_data["吸烟状态"] = None
                                print("吸烟状态:", manzubing_data["吸烟状态"])
                            except Exception as e:
                                manzubing_data["吸烟状态"] = "获取出错"
                                print(f"获取吸烟状态出错: {e}")

                            try:
                                # 日吸烟量
                                sm_amount = tree.xpath('//input[@id="smAmountCur"]/@value')
                                if sm_amount and sm_amount[0].strip():
                                    sm_amount_value = sm_amount[0].strip()
                                    if sm_amount_value == "-1.0":
                                        manzubing_data["日吸烟量"] = "未查"
                                    else:
                                        manzubing_data["日吸烟量"] = float(sm_amount_value)
                                else:
                                    manzubing_data["日吸烟量"] = None
                                print("日吸烟量:", manzubing_data["日吸烟量"])
                            except Exception as e:
                                manzubing_data["日吸烟量"] = "获取出错"
                                print(f"获取日吸烟量出错: {e}")

                            # 运动频率相关信息
                            try:
                                # 低强度运动
                                ex_time_week1 = tree.xpath('//input[@id="exTimeWeek1"]/@value')
                                if ex_time_week1 and ex_time_week1[0].strip():
                                    ex_time_value = ex_time_week1[0].strip()
                                    if ex_time_value == "-1.0":
                                        manzubing_data["低强度运动"] = "未查"
                                    else:
                                        manzubing_data["低强度运动"] = float(ex_time_value)
                                else:
                                    manzubing_data["低强度运动"] = None
                                print("低强度运动:", manzubing_data["低强度运动"])
                            except Exception as e:
                                manzubing_data["低强度运动"] = "获取出错"
                                print(f"获取低强度运动出错: {e}")

                            try:
                                # 中强度运动
                                ex_time_week2 = tree.xpath('//input[@id="exTimeWeek2"]/@value')
                                if ex_time_week2 and ex_time_week2[0].strip():
                                    ex_time_value = ex_time_week2[0].strip()
                                    if ex_time_value == "-1.0":
                                        manzubing_data["中强度运动"] = "未查"
                                    else:
                                        manzubing_data["中强度运动"] = float(ex_time_value)
                                else:
                                    manzubing_data["中强度运动"] = None
                                print("中强度运动:", manzubing_data["中强度运动"])
                            except Exception as e:
                                manzubing_data["中强度运动"] = "获取出错"
                                print(f"获取中强度运动出错: {e}")

                            try:
                                # 高强度运动
                                ex_time_week3 = tree.xpath('//input[@id="exTimeWeek3"]/@value')
                                if ex_time_week3 and ex_time_week3[0].strip():
                                    ex_time_value = ex_time_week3[0].strip()
                                    if ex_time_value == "-1.0":
                                        manzubing_data["高强度运动"] = "未查"
                                    else:
                                        manzubing_data["高强度运动"] = float(ex_time_value)
                                else:
                                    manzubing_data["高强度运动"] = None
                                print("高强度运动:", manzubing_data["高强度运动"])
                            except Exception as e:
                                manzubing_data["高强度运动"] = "获取出错"
                                print(f"获取高强度运动出错: {e}")

                            # 疫苗免疫史相关信息
                            try:
                                # 流感疫苗
                                influenza_vaccine_mapping = {
                                    '0': '无',
                                    '1': '有'
                                }

                                # 查找被选中的流感疫苗单选按钮
                                selected_influenza = tree.xpath(
                                    '//input[@name="influenzaVaccine" and @checked="checked"]/@value')
                                if selected_influenza:
                                    manzubing_data["流感疫苗"] = influenza_vaccine_mapping.get(selected_influenza[0],
                                                                                               "未知")
                                else:
                                    manzubing_data["流感疫苗"] = None

                                # 流感疫苗接种时间
                                influenza_year = tree.xpath('//input[@id="influenzaVaccineY"]/@value')
                                influenza_month = tree.xpath('//input[@id="influenzaVaccineM"]/@value')
                                if influenza_year and influenza_month and influenza_year[0].strip() and influenza_month[
                                    0].strip():
                                    manzubing_data[
                                        "流感疫苗接种时间"] = f"{influenza_year[0].strip()}年{influenza_month[0].strip()}月"
                                else:
                                    manzubing_data["流感疫苗接种时间"] = None

                                print("流感疫苗:", manzubing_data["流感疫苗"])
                                print("流感疫苗接种时间:", manzubing_data["流感疫苗接种时间"])
                            except Exception as e:
                                manzubing_data["流感疫苗"] = "获取出错"
                                manzubing_data["流感疫苗接种时间"] = "获取出错"
                                print(f"获取流感疫苗信息出错: {e}")

                            try:
                                # 肺炎球菌疫苗
                                pneumococcal_vaccine_mapping = {
                                    '0': '无',
                                    '1': '有'
                                }

                                # 查找被选中的肺炎球菌疫苗单选按钮
                                selected_pneumococcal = tree.xpath(
                                    '//input[@name="pneumococcalVaccine" and @checked="checked"]/@value')
                                if selected_pneumococcal:
                                    manzubing_data["肺炎球菌疫苗"] = pneumococcal_vaccine_mapping.get(
                                        selected_pneumococcal[0], "未知")
                                else:
                                    manzubing_data["肺炎球菌疫苗"] = None

                                # 肺炎球菌疫苗接种时间
                                pneumococcal_year = tree.xpath('//input[@id="pneumococcalVaccineY"]/@value')
                                pneumococcal_month = tree.xpath('//input[@id="pneumococcalVaccineM"]/@value')
                                if pneumococcal_year and pneumococcal_month and pneumococcal_year[0].strip() and \
                                        pneumococcal_month[0].strip():
                                    manzubing_data[
                                        "肺炎球菌疫苗接种时间"] = f"{pneumococcal_year[0].strip()}年{pneumococcal_month[0].strip()}月"
                                else:
                                    manzubing_data["肺炎球菌疫苗接种时间"] = None

                                print("肺炎球菌疫苗:", manzubing_data["肺炎球菌疫苗"])
                                print("肺炎球菌疫苗接种时间:", manzubing_data["肺炎球菌疫苗接种时间"])
                            except Exception as e:
                                manzubing_data["肺炎球菌疫苗"] = "获取出错"
                                manzubing_data["肺炎球菌疫苗接种时间"] = "获取出错"
                                print(f"获取肺炎球菌疫苗信息出错: {e}")

                        except Exception as e:
                            print(f"获取生活方式信息出错: {e}")


                        # P7
                        # P7
                        # 获取肺功能信息
                        try:
                            # FEV1（第一秒用力呼气容积）
                            try:
                                fev1_before = tree.xpath('//input[@id="fev1Before"]/@value')
                                if fev1_before and fev1_before[0].strip():
                                    fev1_value = fev1_before[0].strip()
                                    if fev1_value == "-1.0":
                                        manzubing_data["FEV1"] = "未查"
                                    else:
                                        manzubing_data["FEV1"] = float(fev1_value)
                                else:
                                    manzubing_data["FEV1"] = None
                                print("FEV1:", manzubing_data["FEV1"])
                            except Exception as e:
                                manzubing_data["FEV1"] = "获取出错"
                                print(f"获取FEV1出错: {e}")

                            # FVC（用力肺活量）
                            try:
                                fvc = tree.xpath('//input[@id="fev"]/@value')
                                if fvc and fvc[0].strip():
                                    fvc_value = fvc[0].strip()
                                    if fvc_value == "-1.0":
                                        manzubing_data["FVC"] = "未查"
                                    else:
                                        manzubing_data["FVC"] = float(fvc_value)
                                else:
                                    manzubing_data["FVC"] = None
                                print("FVC:", manzubing_data["FVC"])
                            except Exception as e:
                                manzubing_data["FVC"] = "获取出错"
                                print(f"获取FVC出错: {e}")

                            # FEV1/FVC（第一秒用力呼气容积与用力肺活量比值）
                            try:
                                fev1_fvc_before = tree.xpath('//input[@id="fev1FvcBefore"]/@value')
                                if fev1_fvc_before and fev1_fvc_before[0].strip():
                                    fev1_fvc_value = fev1_fvc_before[0].strip()
                                    if fev1_fvc_value == "-1.0":
                                        manzubing_data["FEV1/FVC"] = "未查"
                                    else:
                                        manzubing_data["FEV1/FVC"] = float(fev1_fvc_value)
                                else:
                                    manzubing_data["FEV1/FVC"] = None
                                print("FEV1/FVC:", manzubing_data["FEV1/FVC"])
                            except Exception as e:
                                manzubing_data["FEV1/FVC"] = "获取出错"
                                print(f"获取FEV1/FVC出错: {e}")

                            # FEV1占预计值百分比
                            try:
                                fev1_expect_before = tree.xpath('//input[@id="fev1ExpectBefore"]/@value')
                                if fev1_expect_before and fev1_expect_before[0].strip():
                                    fev1_expect_value = fev1_expect_before[0].strip()
                                    if fev1_expect_value == "-1.0":
                                        manzubing_data["FEV1占预计值百分比"] = "未查"
                                    else:
                                        manzubing_data["FEV1占预计值百分比"] = float(fev1_expect_value)
                                else:
                                    manzubing_data["FEV1占预计值百分比"] = None
                                print("FEV1占预计值百分比:", manzubing_data["FEV1占预计值百分比"])
                            except Exception as e:
                                manzubing_data["FEV1占预计值百分比"] = "获取出错"
                                print(f"获取FEV1占预计值百分比出错: {e}")

                        except Exception as e:
                            print(f"获取肺功能信息出错: {e}")

                        # P8
                        # 合并症前面取过了
                        # P9
                        # mMRC问卷前面已经获取到了
                        # CAT问卷处理 - 简化版本（只保留详情和总分）
                        try:
                            cat_scores = {}
                            cat_questions = {
                                'catCough': '咳嗽',
                                'catHasSputum': '咳痰',
                                'catChestTightness': '胸闷',
                                'catClimbing': '爬坡或爬一层楼梯时的呼吸困难',
                                'catActiveInHome': '在家里的活动受影响程度',
                                'catOutConfidence': '外出信心',
                                'catSleep': '睡眠质量',
                                'catVerdure': '精力状况'
                            }

                            cat_total = 0

                            for question_key, question_desc in cat_questions.items():
                                try:
                                    # 查找被选中的选项
                                    selected_option = tree.xpath(
                                        f'//input[@name="{question_key}" and @checked="checked"]/@value')

                                    if selected_option:
                                        score = int(selected_option[0])
                                        cat_scores[question_desc] = score
                                        cat_total += score
                                    else:
                                        cat_scores[question_desc] = "无"
                                except Exception as e:
                                    cat_scores[question_desc] = "获取出错"

                            # 获取总分
                            try:
                                cat_total_element = tree.xpath('//input[@id="catTotal"]/@value')
                                if cat_total_element:
                                    cat_total_from_page = int(float(cat_total_element[0]))
                                    manzubing_data["CAT问卷总分"] = cat_total_from_page
                                else:
                                    manzubing_data["CAT问卷总分"] = cat_total
                            except Exception as e:
                                manzubing_data["CAT问卷总分"] = "获取出错"

                            # 保存详细评分
                            manzubing_data["CAT问卷"] = cat_scores

                        except Exception as e:
                            manzubing_data["CAT问卷"] = "获取出错"
                            manzubing_data["CAT问卷总分"] = "获取出错"
                        print("CAT问卷:", manzubing_data["CAT问卷"])
                        print("CAT问卷总分:", manzubing_data["CAT问卷总分"])

                        # P10
                        # 呼吸疾病用药呼吸疾病用药不良反应上面获取了
                        # P11
                        # 用药情况上面获取了

                        # P12
                        # P12
                        # 获取家庭氧疗和无创呼吸机使用信息
                        try:
                            # 家庭氧疗
                            try:
                                # 家庭氧疗是否有
                                oxygen_therapy_opt_mapping = {
                                    '0': '无',
                                    '1': '有'
                                }

                                selected_oxygen_therapy = tree.xpath(
                                    '//input[@name="oxygenTherapyOpt" and @checked="checked"]/@value')
                                if selected_oxygen_therapy:
                                    manzubing_data["家庭氧疗"] = oxygen_therapy_opt_mapping.get(selected_oxygen_therapy[0],
                                                                                                "未知")
                                else:
                                    manzubing_data["家庭氧疗"] = None
                                print("家庭氧疗:", manzubing_data["家庭氧疗"])
                            except Exception as e:
                                manzubing_data["家庭氧疗"] = "获取出错"
                                print(f"获取家庭氧疗出错: {e}")

                            try:
                                # 家庭氧疗每日时间
                                oxygen_therapy_time = tree.xpath('//input[@id="oxygenTherapyTime"]/@value')
                                if oxygen_therapy_time and oxygen_therapy_time[0].strip():
                                    oxygen_time_value = oxygen_therapy_time[0].strip()
                                    if oxygen_time_value == "-1.0":
                                        manzubing_data["家庭氧疗每日时间"] = "未查"
                                    else:
                                        manzubing_data["家庭氧疗每日时间"] = float(oxygen_time_value)
                                else:
                                    manzubing_data["家庭氧疗每日时间"] = None
                                print("家庭氧疗每日时间:", manzubing_data["家庭氧疗每日时间"])
                            except Exception as e:
                                manzubing_data["家庭氧疗每日时间"] = "获取出错"
                                print(f"获取家庭氧疗每日时间出错: {e}")

                            try:
                                # 家庭氧疗氧流量
                                oxygen_therapy_flow = tree.xpath('//input[@id="oxygenTherapyFlow"]/@value')
                                if oxygen_therapy_flow and oxygen_therapy_flow[0].strip():
                                    oxygen_flow_value = oxygen_therapy_flow[0].strip()
                                    if oxygen_flow_value == "-1.0":
                                        manzubing_data["家庭氧疗氧流量"] = "未查"
                                    else:
                                        manzubing_data["家庭氧疗氧流量"] = float(oxygen_flow_value)
                                else:
                                    manzubing_data["家庭氧疗氧流量"] = None
                                print("家庭氧疗氧流量:", manzubing_data["家庭氧疗氧流量"])
                            except Exception as e:
                                manzubing_data["家庭氧疗氧流量"] = "获取出错"
                                print(f"获取家庭氧疗氧流量出错: {e}")

                            try:
                                # 家庭氧疗副作用
                                oxygen_therapy_effect_mapping = {
                                    '0': '无',
                                    '1': '有'
                                }

                                selected_oxygen_effect = tree.xpath(
                                    '//input[@name="oxygenTherapyEffect" and @checked="checked"]/@value')
                                if selected_oxygen_effect:
                                    manzubing_data["家庭氧疗副作用"] = oxygen_therapy_effect_mapping.get(
                                        selected_oxygen_effect[0], "未知")
                                else:
                                    manzubing_data["家庭氧疗副作用"] = None
                                print("家庭氧疗副作用:", manzubing_data["家庭氧疗副作用"])
                            except Exception as e:
                                manzubing_data["家庭氧疗副作用"] = "获取出错"
                                print(f"获取家庭氧疗副作用出错: {e}")

                            try:
                                # 家庭氧疗副作用描述
                                oxygen_therapy_effect_des = tree.xpath('//input[@id="oxygenTherapyEffectDes"]/@value')
                                if oxygen_therapy_effect_des:
                                    effect_des_value = oxygen_therapy_effect_des[0].strip()
                                    manzubing_data["家庭氧疗副作用描述"] = effect_des_value if effect_des_value else None
                                else:
                                    manzubing_data["家庭氧疗副作用描述"] = None
                                print("家庭氧疗副作用描述:", manzubing_data["家庭氧疗副作用描述"])
                            except Exception as e:
                                manzubing_data["家庭氧疗副作用描述"] = "获取出错"
                                print(f"获取家庭氧疗副作用描述出错: {e}")

                            # 无创呼吸机使用
                            try:
                                # 无创呼吸机使用是否有
                                respirator_cure_opt_mapping = {
                                    '0': '无',
                                    '1': '有'
                                }

                                selected_respirator = tree.xpath(
                                    '//input[@name="respiratorCureOpt" and @checked="checked"]/@value')
                                if selected_respirator:
                                    manzubing_data["无创呼吸机使用"] = respirator_cure_opt_mapping.get(
                                        selected_respirator[0], "未知")
                                else:
                                    manzubing_data["无创呼吸机使用"] = None
                                print("无创呼吸机使用:", manzubing_data["无创呼吸机使用"])
                            except Exception as e:
                                manzubing_data["无创呼吸机使用"] = "获取出错"
                                print(f"获取无创呼吸机使用出错: {e}")

                            try:
                                # 无创呼吸机使用每日时间
                                respirator_cure_time = tree.xpath('//input[@id="respiratorCureTime"]/@value')
                                if respirator_cure_time and respirator_cure_time[0].strip():
                                    cure_time_value = respirator_cure_time[0].strip()
                                    if cure_time_value == "-1.0":
                                        manzubing_data["无创呼吸机使用每日时间"] = "未查"
                                    else:
                                        manzubing_data["无创呼吸机使用每日时间"] = float(cure_time_value)
                                else:
                                    manzubing_data["无创呼吸机使用每日时间"] = None
                                print("无创呼吸机使用每日时间:", manzubing_data["无创呼吸机使用每日时间"])
                            except Exception as e:
                                manzubing_data["无创呼吸机使用每日时间"] = "获取出错"
                                print(f"获取无创呼吸机使用每日时间出错: {e}")

                            try:
                                # 无创呼吸机使用氧流量
                                respirator_cure_flow = tree.xpath('//input[@id="respiratorCureFlow"]/@value')
                                if respirator_cure_flow and respirator_cure_flow[0].strip():
                                    cure_flow_value = respirator_cure_flow[0].strip()
                                    if cure_flow_value == "-1.0":
                                        manzubing_data["无创呼吸机使用氧流量"] = "未查"
                                    else:
                                        manzubing_data["无创呼吸机使用氧流量"] = float(cure_flow_value)
                                else:
                                    manzubing_data["无创呼吸机使用氧流量"] = None
                                print("无创呼吸机使用氧流量:", manzubing_data["无创呼吸机使用氧流量"])
                            except Exception as e:
                                manzubing_data["无创呼吸机使用氧流量"] = "获取出错"
                                print(f"获取无创呼吸机使用氧流量出错: {e}")

                            try:
                                # 无创呼吸机使用副作用
                                respirator_cure_effect_mapping = {
                                    '0': '无',
                                    '1': '有'
                                }

                                selected_respirator_effect = tree.xpath(
                                    '//input[@name="respiratorCureEffect" and @checked="checked"]/@value')
                                if selected_respirator_effect:
                                    manzubing_data["无创呼吸机使用副作用"] = respirator_cure_effect_mapping.get(
                                        selected_respirator_effect[0], "未知")
                                else:
                                    manzubing_data["无创呼吸机使用副作用"] = None
                                print("无创呼吸机使用副作用:", manzubing_data["无创呼吸机使用副作用"])
                            except Exception as e:
                                manzubing_data["无创呼吸机使用副作用"] = "获取出错"
                                print(f"获取无创呼吸机使用副作用出错: {e}")

                            try:
                                # 无创呼吸机使用副作用描述
                                respirator_cure_effect_des = tree.xpath('//input[@id="respiratorCureEffectDes"]/@value')
                                if respirator_cure_effect_des:
                                    effect_des_value = respirator_cure_effect_des[0].strip()
                                    manzubing_data[
                                        "无创呼吸机使用副作用描述"] = effect_des_value if effect_des_value else None
                                else:
                                    manzubing_data["无创呼吸机使用副作用描述"] = None
                                print("无创呼吸机使用副作用描述:", manzubing_data["无创呼吸机使用副作用描述"])
                            except Exception as e:
                                manzubing_data["无创呼吸机使用副作用描述"] = "获取出错"
                                print(f"获取无创呼吸机使用副作用描述出错: {e}")

                        except Exception as e:
                            print(f"获取家庭氧疗和无创呼吸机使用信息出错: {e}")

                        # P13
                        # P13
                        # 获取转诊信息
                        try:
                            # 是否转诊
                            try:
                                referral_mapping = {
                                    '0': '否',
                                    '1': '是'
                                }

                                selected_referral = tree.xpath('//input[@name="referral" and @checked="checked"]/@value')
                                if selected_referral:
                                    manzubing_data["是否转诊"] = referral_mapping.get(selected_referral[0], "未知")
                                else:
                                    manzubing_data["是否转诊"] = None
                                print("是否转诊:", manzubing_data["是否转诊"])
                            except Exception as e:
                                manzubing_data["是否转诊"] = "获取出错"
                                print(f"获取是否转诊出错: {e}")

                            # 转诊原因
                            try:
                                referral_reason = tree.xpath('//input[@id="referralReason"]/@value')
                                if referral_reason:
                                    reason_value = referral_reason[0].strip()
                                    manzubing_data[
                                        "转诊原因"] = reason_value if reason_value else None
                                else:
                                    manzubing_data["转诊原因"] = None
                                print("转诊原因:", manzubing_data["转诊原因"])
                            except Exception as e:
                                manzubing_data["转诊原因"] = "获取出错"
                                print(f"获取转诊原因出错: {e}")

                            # 机构及科别
                            try:
                                referral_org_dept = tree.xpath('//input[@id="referralOrgDept"]/@value')
                                if referral_org_dept:
                                    org_dept_value = referral_org_dept[0].strip()
                                    manzubing_data[
                                        "机构及科别"] = org_dept_value if org_dept_value else None
                                else:
                                    manzubing_data["机构及科别"] = None
                                print("机构及科别:", manzubing_data["机构及科别"])
                            except Exception as e:
                                manzubing_data["机构及科别"] = "获取出错"
                                print(f"获取机构及科别出错: {e}")

                        except Exception as e:
                            print(f"获取转诊信息出错: {e}")

                        all_infomation.append(manzubing_data)

        return all_infomation # 返回完整数据和提取的数据
    #
    except:
        print(f"处理失败: {id_person}, 错误: 获取信息时报错了")
        return None


if __name__ == '__main__':
    headers_8 = {
    "cookie": "JSESSIONID=3BB9AD49356A1A25B90283A7AA5C266A",
}
    print(manzufeidownload1("610303195102071611","c29a7a11-43e9-45ea-9e1e-6c6fdaaf42c4",headers_8,"http://10.216.11.24:8306","2025-01-01","2025-12-31",{"随访类型":"高血压,糖尿病"}))
